﻿using DotNetStar.TheKing.Infrastructure;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DotNetStar.TheKing.Services
{
    public abstract class ServiceBase
    {
        protected ServiceBase(IMemoryCache memoryCache)
        {
            MemoryCache = memoryCache;
        }

        protected IMemoryCache MemoryCache { get; }

        /// <summary>
        /// 将指定的结果优先从缓存中读取。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存键。</param>
        /// <param name="func">这是一个委托，表示返回值将会设置到缓存中。</param>
        /// <param name="force">是否强制更新指定键的缓存。</param>
        /// <returns></returns>
        protected Task<T> GetFromCacheAsync<T>(string key, Func<T> func, bool force = false)
        {
            //暂时不做缓存处理
            return Task.FromResult(func());

            //if (force)
            //{
            //    SetToCache(key, func);
            //}
            //T value;
            //if (MemoryCache.TryGetValue(key, out T val))
            //{
            //    value = val;
            //}
            //else {

            //    value = func();
            //    MemoryCache.Set(key, value);
            //}

            //return Task.FromResult(value);

            //return MemoryCache.GetOrCreateAsync<T>(key, m =>
            //{
            //    return Task.FromResult(func());
            //});
        }

        protected void SetToCache<T>(string key,Func<T> func)
        {
            MemoryCache.Set(key, func());
        }

        protected void SetToCache<T>(string key, T value) => SetToCache(key, () => value);

        /// <summary>
        /// 移除指定的缓存
        /// </summary>
        /// <param name="key">缓存的键。</param>
        protected void RemoveFromCache(string key) => this.MemoryCache.Remove(key);
    }
}
